package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.common.dtos.PageResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.feign.client.ArticleFeign;
import com.heima.feign.client.WmediaFeign;
import com.heima.model.article.dtos.AuthorDto;
import com.heima.model.media.dtos.WmUserDto;
import com.heima.model.user.dtos.AuthDto;
import com.heima.user.entity.ApUser;
import com.heima.user.entity.ApUserAuth;
import com.heima.user.mapper.ApUserAuthMapper;
import com.heima.user.service.ApUserAuthService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.user.service.ApUserService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.ExceptionHandler;

import java.lang.invoke.LambdaConversionException;
import java.util.Date;

/**
 * <p>
 * APP实名认证信息表 服务实现类
 * </p>
 *
 * @author HM
 * @since 2023-02-15
 */
@Service
public class ApUserAuthServiceImpl extends ServiceImpl<ApUserAuthMapper, ApUserAuth> implements ApUserAuthService {

    /**
     * 查询用户认证列表
     * @param dto
     * @return
     */
    @Override
    public PageResult<ApUserAuth> authList(AuthDto dto) {
//        设置分页条件
        Page<ApUserAuth> ipage = new Page<>(dto.getPage(), dto.getSize());
//        设置查询条件
//        select * from ap_user_auth where status =?
        LambdaQueryWrapper<ApUserAuth> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dto.getStatus() != null,ApUserAuth::getStatus,dto.getStatus());
//        分页查询
        Page<ApUserAuth> apUserAuthPage = this.page(ipage, queryWrapper);
        if(CollectionUtils.isEmpty(apUserAuthPage.getRecords())){
//            结果为空
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
//        构造返回对象
        PageResult<ApUserAuth> pageResult = new PageResult<>(dto.getPage(),
                dto.getSize(),
                apUserAuthPage.getTotal(),
                apUserAuthPage.getRecords());
        return pageResult;
    }

    @Autowired
    private WmediaFeign wmediaFeign;
    @Autowired
    private ArticleFeign articleFeign;
    @Autowired
    private ApUserService apUserService;

    @Override
    //@Transactional(rollbackFor = Exception.class) 本地事务
    @GlobalTransactional(rollbackFor = Exception.class) //全局事务
    public void userAuth(AuthDto dto, int status) {
//        根据审核的id，修改审核信息的状态
//        update ap_user_auth set status=? where id=?
        ApUserAuth apUserAuth = new ApUserAuth();
        apUserAuth.setId(dto.getId());
        apUserAuth.setStatus(status);
//        设置不通过的原因
        apUserAuth.setReason(dto.getMsg());
        apUserAuth.setUpdatedTime(new Date());
//        修改
        boolean b = updateById(apUserAuth);
//        判断是否通过
        if(status ==2){
//            审核不通过,结束
            return;
        }
//        根据auth_id 查auth对象，获取apUserId
        apUserAuth = getById(dto.getId());
        Integer apUserId = apUserAuth.getUserId();
//        根据apUserId主键查询apUser对象数据
        ApUser apUser = apUserService.getById(apUserId);
        if(apUser == null){
            log.error("查询apuser失败！回滚");
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
//        远程调用 wemedia,返回自媒体用户id
        WmUserDto wmUserDto = new WmUserDto();
        wmUserDto.setApUserId(apUserId);
        wmUserDto.setName(apUser.getName());
        wmUserDto.setPassword(apUser.getPassword());
        wmUserDto.setPhone(apUser.getPhone());
        wmUserDto.setStatus(9);
        try {
            Integer wmUserId = wmediaFeign.saveWmUser(wmUserDto);
            wmUserDto.setId(wmUserId);
        }catch (Exception e){
            log.error("调用自媒体服务失败！");
            e.printStackTrace();
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR);
        }
//        远程调用 article,返回文章作者id
        AuthorDto authorDto = new AuthorDto();
        authorDto.setName(apUser.getName());
        authorDto.setUserId(apUserId);
        authorDto.setType(2);
        authorDto.setWmUserId(wmUserDto.getId());
        try {
            Integer authorId = articleFeign.saveAuthor(authorDto);
        }catch (Exception e){
            log.error("调用article服务失败！");
            e.printStackTrace();
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR);
        }
//        重新创建Apuser，实现修改flag的值
        apUser = new ApUser();
        apUser.setId(apUserId);
        apUser.setFlag(1);
//        修改apUser表的flag，改成1
        boolean b1 = apUserService.updateById(apUser);
        if(!b1){
            log.error("更新flag失败");
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR);
        }
        //System.out.println(1/0);
    }
}
